import datetime

import redis

# 配置 Redis 连接
redis_host = '192.168.15.57'  # 测试
# redis_host = '172.22.128.51'
redis_port = 6379
# redis_port = 38152
# redis_pwd = 'zDocpWPgLaoBv@VE'
redis_pwd = ''


def get_elements_after_input(element, my_list):
    element = element.split(':')[-1]
    if element in my_list:
        index = my_list.index(element)
        return my_list[:index + 2]
    else:
        return []


# 连接到Redis数据库
class RedisApi:
    def __init__(self, host, port, password, db):
        self.host = host
        self.port = port
        self.password = password
        self.db = db

    @property
    def conn(self):
        try:
            return redis.Redis(host=self.host, port=self.port, password=self.password, db=self.db, socket_timeout=3)
        except Exception as e:
            print(e)
            return False

    @property
    def ok(self):
        try:
            self.conn.keys()
            return True
        except Exception as e:
            print(e)
            return False

    @property
    def keys(self):
        key_list = self.conn.keys()
        key_list = [{"key": i.decode()} for i in key_list]
        return key_list

    def type(self, key):
        re_type = self.conn.type(key).decode()
        re_type = "" if re_type == "none" else re_type
        return re_type

    def get_keys(self, path=None):
        key_list = []
        keys = self.conn.keys()
        keys = [i.decode() for i in keys]
        for key in keys:
            if not path:
                key = key.split(':')[0]
                if key:
                    key_list.append(key)
            else:
                if path in key:
                    key = key.split(':')
                    key_query = get_elements_after_input(path, key)
                    key_path = ':'.join(key_query)
                    if key_path:
                        key_list.append(key_path)

        key_list = list(set(key_list))
        key_list = [{"key": i, "type": ""} for i in key_list]
        for i in key_list:
            if i['key'] in keys:
                i["type"] = self.type(i["key"])
        return key_list

    def get_redis_list(self, LogName=None, page=10000):
        max_length = self.conn.llen(LogName)
        min_length = max_length - page
        min_length = 0 if min_length <= 0 else min_length
        latest_data = self.conn.lrange(LogName, min_length, max_length)
        latest_data_strings = [item.decode('utf-8') for item in latest_data]
        return latest_data_strings

    def complete_data(self, item, query, start=0, all=True, search_keyword=None):
        index = start
        for element in query:
            index += 1
            content = element.decode('utf-8')
            search_dict = {
                "index": index,
                "data": content
            }
            if all is True:
                item.append(search_dict)
            else:
                if search_keyword in content:
                    item.append(search_dict)
        return item

    def get_redis_search_range(self, LogName=None, all=False, search_keyword=None, limit=None):
        search_list = []
        result_list = []
        all_elements = self.conn.lrange(LogName, 0, -1)
        search_list = self.complete_data(
            search_list, all_elements, all=all, search_keyword=search_keyword)
        if all is True:
            start, end = search_list[0]['index'], search_list[-1]['index']
            all_data = self.conn.lrange(LogName, start, end)
            result_list = self.complete_data(
                result_list, all_data, start, all, search_keyword=search_keyword)
            return result_list
        else:
            return search_list

    def get_redis_search_date(self, LogName=None, start_time=None, end_time=None, limit=None):
        search_list = []
        result_list = []
        all_elements = self.conn.lrange(LogName, 0, 1)
        # 定义时间字符串的格式
        time_format = "%Y-%m-%d %H:%M:%S"
        # 将字符串转换为时间对象
        start_time = datetime.datetime.strptime(start_time, time_format)
        end_time = datetime.datetime.strptime(end_time, time_format)
        for item in all_elements:
            item_time = datetime.datetime.strptime(
                item.decode('utf-8').split(' |')[0][:-4], time_format)
            if start_time > item_time and end_time < item_time:
                search_list.append(item)
        return search_list

    def get_refush_search(self, LogName, limit):
        return self.get_redis_search_range(LogName=LogName, limit=limit)

    def get_zset(self, key):
        zset_list = []
        result = self.conn.zrange(key, 0, -1, withscores=True)
        for query in result:
            data = query[0].decode()
            zset_list.append(
                {"data": data}
            )
        return zset_list

    def get_string(self, key):
        string_list = []
        string_data = self.conn.get(key)
        # 解码并打印字符串数据
        if string_data is not None:
            decoded_data = string_data.decode('utf-8')
            string_list.append(
                {"data": decoded_data}
            )
        else:
            string_list.append(
                {"data": "String data not found."}
            )
        return string_list
